<?php
/**
 * Description: 行测 - 找数作业模块
 * User: devforma
 * Date: 16/7/27
 * Time: 12:05
 */

require __DIR__ . '/ProcessExerciseBase.class.php';

class ZhaoshuModule extends ProcessExerciseBase {

    /**
     * 设置作业类型
     */
    protected function setExerciseType() {
        $this->data['exercise_type'] = 32;
    }

    /**
     * 设置作业题目
     */
    protected function setExerciseQuestion() {
        global $cmsdb;

        //获取题目信息
        $qids = implode(',', $this->questionIds);
        $sql = "SELECT * FROM `original_primary_question` WHERE `id` IN ({$qids}) ORDER BY FIELD (`id`, {$qids})";
        $questions = $cmsdb->getResults($sql);

        $list = [];
        foreach ($questions as $q) {

            //问题和答案合并
            $options = explode('#', $q->options);
            $answers = explode('#', $q->right_answer);
            $questions = [];
            foreach ($options as $index => $option) {
                $questions[] = [
                    'option' => $option,
                    'answer' => $answers[$index]
                ];
            }

            $list[] = [
                'question_id' => (int)$q->id,
                'question'    => $q->content,
                'options'     => $questions,
                'analysis'    => (string)$q->analysis
            ];
        }

        $this->data['question'] = $list;
    }

    /**
     * 设置提交权限
     */
    protected function setSubmitPriv() {
        parent::setSubmitPriv();
    }

    /**
     * 设置用户答案
     */
    protected function setUserAnswer() {
        global $uddb;

        //查询用户做题记录
        $sql = 'SELECT * FROM `history_user_primary_question` WHERE `exercise_id`=:eid AND `user_id`=:uid';
        $records = $uddb->getResults($sql, [':eid' => $this->exerciseId, ':uid' => $this->userId]);
        $answers = [];
        foreach ($records as $r) {
            $answers[$r->question_id] = json_decode($r->user_answer);
        }

        //合并用户答案
        foreach ($this->data['question'] as &$question) {
            foreach ($question['options'] as $index => &$opt) {
                $opt['user_answer'] = $answers[$question['question_id']][$index];
            }
        }
    }

    /**
     * 设置作业的统计信息
     */
    protected function setSummary() {

        $exerciseInfo = $this->exerciseInfo;
        $className    = getClassName($exerciseInfo->calss_id);
        $courseName   = getCourseName($exerciseInfo->course_id);

        $historyExercise = VipUtils::getHistoryUserPrimaryExerciseInfo($this->exerciseId,$this->userId);
        $data = json_decode($historyExercise->summary,true);

        $this->data['summary'] = json_decode($this->userExerciseRecord->summary);
        $this->data['level']            = (int)$exerciseInfo->summary;
        $this->data['class_name']       = !empty($className) ? $className : '所有课堂';
        $this->data['course_name']      = !empty($courseName) ? $courseName : '所有课程';
        $this->data['exercise_name']    = $exerciseInfo->name;
        $this->data['fastest']          = VipUtils::getFastest(['type_id' => $exerciseInfo->type_id,'is_arr' => 2]);
        $this->data['ranking']          = !empty($data['ranking']) ? $data['ranking'] : 0;
    }

    /**
     * 检测提交的参数
     * @param array $args 参数
     * @return bool
     */
    public function validateArgs($args) {
        if (!empty($args['answer_content']) && !empty($args['duration'])) {
            $this->submitArgs = $args;
            return true;
        }

        return false;
    }

    /**
     * 提交 - 设置作业状态
     */
    protected function setSubmitStatus() {
        if ($this->exerciseInfo->end_time > $this->now)
            $this->submitExerciseRecord['status'] = 1; //已完成
        else
            $this->submitExerciseRecord['status'] = 5; //过期完成
    }

    /**
     * 提交 - 保存答题记录及设置作业统计信息
     */
    protected function saveQuestionRecordsAndSetSubmitSummary() {
        global $uddb;

        $answers = json_decode($this->submitArgs['answer_content']);

        $total = $right = 0;
        foreach ($answers as $a) {

            //统计答对、总题目数量
            foreach ($a->options as $child) {
                if ($child->is_right)
                    $right++;

                $total++;
            }

            //构造数据结构
            $questionRecord = [
                'question_id' => $a->question_id,
                'exercise_id' => $this->exerciseId,
                'user_id'     => $this->userId,
                'acting_time' => $this->now,
                'user_answer' => json_encode($a->options),
                'is_right'    => 1,
                'status'      => 1
            ];

            $uddb->insert('history_user_primary_question', $questionRecord);
        }


        if ($total == $right && $right != 0) {

            //记录是第几个完成作业的人
            VipUtils::setRanking($this->submitArgs);

            //返回值格式
            $this->submitArgs['is_arr'] = 2;
            //作业类型
            $this->submitArgs['type_id'] = $this->exerciseInfo->type_id;

            //更新全站通关最快时间
            $fastest = VipUtils::getFastest($this->submitArgs);
            if (empty($fastest) || $fastest >= $this->submitArgs['duration'])
                VipUtils::setFastest($this->submitArgs);


            //更新个人通关最快时间
            $fastestSelf = VipUtils::getFastestSelf($this->submitArgs);
            if (empty($fastestSelf) || $fastestSelf >= $this->submitArgs['duration'])
                VipUtils::setFastestSelf($this->submitArgs);

        }
        //获取是第几个完成作业的人
        $ranking = VipUtils::getRanking($this->submitArgs);

        //更新已做人数
        $this->updateXingcePersonsNum();

        //保存统计信息
        $this->submitExerciseRecord['summary'] = json_encode([
            'position'     => $this->getXingcePersonsNum(),
            'duration'     => (int)$this->submitArgs['duration'],
            'accuracy'     => round($right/$total, 3),
            'avg_duration' => round($this->submitArgs['duration']/$total),
            'ranking'      => $ranking
        ]);
    }

    /**
     * 获取自测题目
     *
     * @param array $ids 题目id
     * @param array $userAnswers
     * @return null
     */
    protected function getSelfTestQuestions($ids, &$userAnswers) {
        global $cmsdb;

        $string = implode(',', $ids);
        $questions = $cmsdb->getResults("SELECT * FROM `original_primary_question` WHERE `id` IN ({$string}) ORDER BY FIELD(`id`, {$string})");

        $list = [];
        foreach ($questions as $q) {

            //问题和答案合并
            $options = explode('#', $q->options);
            $answers = explode('#', $q->right_answer);
            $questions = [];

            if (isset($userAnswers[$q->id])) { //答题报告取题
                $uAnswer = json_decode($userAnswers[$q->id]);
                foreach ($options as $index => $option) {
                    $questions[] = [
                        'option'      => $option,
                        'answer'      => $answers[$index],
                        'user_answer' => $uAnswer[$index]
                    ];
                }
            } else {
                foreach ($options as $index => $option) {
                    $questions[] = [
                        'option' => $option,
                        'answer' => $answers[$index]
                    ];
                }
            }

            $list[] = [
                'question_id' => (int)$q->id,
                'question'    => $q->content,
                'options'     => $questions
            ];
        }

        return $list;
    }

    /**
     * 通关时间--全站\个人
     *
     * @param $args
     * @return array
     */
    protected function getFastestData($args) {

        $args['is_arr'] = 1;

        $fastest     = VipUtils::getFastest($args);
        $fastestSelf = VipUtils::getFastestSelf($args);

        $result = [];
        foreach ($fastest as $k => $v) {
            $result['level_'.$k] = [
                'fastest'       => $v,
                'fastest_self'  => !empty($fastestSelf[$k]) ? $fastestSelf[$k] : null
            ];
        }
        return $result;
    }

    /**
     * 提交自测记录
     *
     * @param array $args
     * @return null
     */
    public function submitSelfTest($args) {
        global $uddb;

        $answers = json_decode($args['answer_content']);

        $total = $right = 0;
        $records = [];
        foreach ($answers as $a) {

            //统计答对、总题目数量
            foreach ($a->options as $child) {
                if ($child->is_right)
                    $right++;

                $total++;
            }

            //构造数据结构
            $questionRecord = [
                'question_id' => $a->question_id,
                'exercise_id' => 0,
                'user_id'     => $args['user_id'],
                'acting_time' => $this->now,
                'user_answer' => json_encode($a->options),
                'is_right'    => 1,
                'status'      => 1
            ];

            $uddb->insert('history_user_primary_question', $questionRecord);

            $records[] = $uddb->lastInsertId();
        }

        $summary = [
            'duration'     => (int)$args['duration'],
            'accuracy'     => round($right/$total, 3),
            'avg_duration' => round($args['duration']/$total)
        ];

        //自测记录
        $uddb->insert('history_user_primary_selftest', [
            'user_id'     => $args['user_id'],
            'type_id'     => 32,
            'action_time' => $this->now,
            'records'     => implode(',', $records),
            'summary'     => json_encode($summary)
        ]);

        $summary['selftest_id'] = (int)$uddb->lastInsertId();

        //更新最快时间
        if ($total == $right && $right != 0) {

            $args['is_arr'] = 2;
            $fastest        = VipUtils::getFastest($args);
            $fastestSelf    = VipUtils::getFastestSelf($args);

            //更新个人通关最快时间
            if (empty($fastestSelf) || $fastestSelf >= $args['duration'])
                VipUtils::setFastestSelf($args);


            //更新全站通关最快时间
            if (empty($fastest) || $fastest >= $args['duration'])
                VipUtils::setFastest($args);

        }

        //统计信息

        return $summary;
    }
}